// pages/uc/contract_signing_new/contract_signing_new.js
var dmNetwork = require("../../utils/network.js");
Page({
  data: {
    contractTxt: "",
    contract_list: [],
    isShowSendCodeView: false,
    getcodetext: "获取验证码",
    getcodestatus: false,
    agingetcode: true,
    msmcode: "",
    cont_protocol_order_id: "",
    can_send_code_flag: true,
    latitude: "",
    longitude: "",
    team_id: "",
    project_id: "",
    contract_list: [],
    currentContract: {},
    protocol_order_ids: [],
    report_contract_no:'', // 青桔协议编号
    is_protocol_supplement_info:'',
    is_upload_idcard_info:'',
    sign_channel:'',
    is_ocr_check:'',
    group_id:'',
    is_social:'',
    ifNeedAuthFlag:false,
    optionsData:{}
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      team_id: options.team_id,
      project_id: options.project_id,
      optionsData:options
    });
    this.getStep();
  },
  getStep() {
    const that = this;
    let request_data = {
      team_id: this.data.team_id,
      project_id: this.data.project_id,
    };
    dmNetwork.post(dmNetwork.check_protocol, request_data, (res) => {
      if (res.data.errno == 0) {
        const data = res.data.data;
        const report_contract_no = data.report_contract_no;
        const contractList = data.protocol_order_ids;
        const currentContract = contractList.shift();

        const protocol_order_ids = that.data.protocol_order_ids;
        protocol_order_ids.push(currentContract.protocol_order_id);
        const ifNeedAuthFlag =
      data.protocol_order_ids.length > 0 && data.is_complete_user == 1;
        that.setData({
          contract_list: contractList,
          currentContract: currentContract,
          protocol_order_ids: protocol_order_ids,
          report_contract_no,
          ifNeedAuthFlag
        });
        // if (currentContract.is_authorize_location === 1) {
        //   this.getLocation();
        // }
        that.getTemplate(report_contract_no);
      } else {
        wx.showToast({
          title: res.data.errmsg,
          icon: "none",
        });
      }
    });
  },
  getTemplate(currentContract) {
    const that = this;
    let request_data = {
      dmclient: "weixinxcx",
      sign: "",
      team_id: this.data.team_id,
      contract_no: currentContract,
    };
    dmNetwork.post(dmNetwork.get_template, request_data, (res) => {
      if (res.data.errno == 0) {
        const data = res.data.data;
        const tab = data.content.xcx_content.replace(/<table/g,'<table class="table"').replace(/<tr/g,'<tr class="trt"').replace(/<td/g,'<td class="tdd"').replace(/<th/g,'<th class="thh"')
        that.setData({
          contractTxt: tab,
        });
      } else {
        wx.showToast({
          title: res.data.errmsg,
          icon: "none",
        });
      }
    });
  },
  getLocation: function () {
    let that = this;
    wx.getLocation({
      type: "wgs84",
      success(res) {
        const latitude = res.latitude;
        const longitude = res.longitude;
        that.setData({
          latitude: latitude,
          longitude: longitude,
        });
      },
      fail(err) {
        wx.showToast({
          title: "授权位置后才可签约",
          icon: "none",
          duration: 2000,
        });
      },
    });
  },
  next: function (options) {
    const status = options.currentTarget.dataset.status;
    this.setData({
      selectedStatus: status
    });
    
    const that = this;
    var request_data = {
      team_id: that.data.team_id,
      project_id: that.data.project_id,
      status
    };
    dmNetwork.post(dmNetwork.report, request_data, (res) => {
      if (res.data.errno == 0) {
        if(status == 1){
          this.setData({
            isShowSendCodeView: true
          })
          return
        }
        this.contractSigningNew()
      } else {
        wx.showToast({
          title: res.data.errmsg,
          icon: "none",
        });
      }
    });
  },

  confirm_next: function (options) {
    this.setData({
      isShowSendCodeView: false
    })
    const that = this;
    const status = options.currentTarget.dataset.status;
    var request_data = {
      team_id: that.data.team_id,
      project_id: that.data.project_id,
      status
    };
    dmNetwork.post(dmNetwork.report, request_data, (res) => {
      if (res.data.errno == 0) {
        if(status == 1){
          wx.navigateBack({
            delta: 1
          })
          return
        }
      } else {
        wx.showToast({
          title: res.data.errmsg,
          icon: "none",
        });
      }
    });
  },

  cancel: function (options) {
    this.setData({
      isShowSendCodeView: false,
      msmcode: "",
    });
  },
  contractSigningNew:function(){
    const localProjectId = wx.getStorageSync("local_project_id");
    const localTeamId = wx.getStorageSync("team_id");
    // project_id=17429&team_id=10&is_protocol_supplement_info=undefined&is_upload_idcard_info=undefined&is_ocr_check=undefined&group_id=45733&is_social=undefined&sign_channel=undefined
    const params = `project_id=${localProjectId}&team_id=${localTeamId}&is_protocol_supplement_info=${this.data.optionsData.is_protocol_supplement_info}&is_upload_idcard_info=${this.data.optionsData.is_upload_idcard_info}&is_ocr_check=${this.data.optionsData.is_ocr_check}&group_id=${this.data.optionsData.group_id}&is_social=${this.data.optionsData.is_social}&sign_channel=${this.data.optionsData.sign_channel}`;

    let protocol_order_id = "";
    if(this.data.optionsData.sign_channel == 1){
      this.data.protocol_order_ids
      .forEach((element) => {
        protocol_order_id += element.protocol_order_id + ",";
      });

    }else{
      this.data.protocol_order_ids
      .filter((item) => {
        return item.is_protocol_supplement_info == 1;
      })
      .forEach((element) => {
        protocol_order_id += element.protocol_order_id + ",";
      });
    }
    protocol_order_id = protocol_order_id.substring(0,protocol_order_id.length - 1);
    const navigateUrl = this.data.ifNeedAuthFlag
      ? `../uc/perfect_information/perfect_information?${params}&protocol_order_id=${protocol_order_id}`
      : `../uc/contract_signing_new/contract_signing_new?${params}`;
    wx.navigateTo({
      url: navigateUrl,
    });
    // wx.navigateBack({
    //   delta: 1
    // })
  },

  bindCodeInput: function (e) {
    var value = e.detail.value;
    var newVal = value.replace(/\D/g, "").replace(/\s/g, "");
    if (typeof +newVal != "number") {
      return newVal;
    }
    if (newVal.length === 6) {
      this.setData({
        msmcode: newVal,
      });
    }
  },

  // 获取验证码请求
  getcode: function () {
    if (!this.data.can_send_code_flag) {
      return;
    }
    var that = this;
    that.setData({
      can_send_code_flag: false,
    });
    var request_data = {
      team_id: that.data.team_id,
      project_id: that.data.project_id,
    };
    dmNetwork.get(dmNetwork.protocol_msg_get, request_data, (res) => {
      if (res.data.errno == 0) {
        wx.showToast({
          title: "发送成功!",
          success: () => {
            var time = 60;
            that.setData({
              getcodetext: "60s",
              getcodestatus: true,
              agingetcode: false,
            });
            var thetimer = setInterval(function () {
              that.setData({
                getcodetext: --time + "s",
              });
              if (time === -1) {
                clearInterval(thetimer);
                that.setData({
                  getcodetext: "重新获取",
                  getcodestatus: true,
                  agingetcode: true,
                  can_send_code_flag: true,
                });
              }
            }, 1000);
          },
        });
      }
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (this.data.currentContract.is_authorize_location === 1) {
      this.getLocation();
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},
});
